using System;
using FireStarterModeller.BO;
using FireStarterModeller.Logic;
using Habanero.Base;
using Habanero.BO;
using Habanero.BO.ClassDefinition;
using Habanero.Faces.Base;
using Habanero.Faces.Win;

namespace FireStarterModeller.UI.Relationship
{
    /// <summary>
    /// This wizard step is the first step for creating a new <see cref="DMRelationship"/>. 
    /// In this wizard step the user selects the Related Business Object
    /// from this the system will try to determine the relationshipName, related properties etc.
    /// 
    /// In this step you select the Related Class.
    /// </summary>
    public class CreateRelationshipWizardStep1 : WizardStepWin
    {
        private DMRelationshipCreator RelationshipCreator { get; set; }
        private readonly IDMClass _ownerClass;
        private readonly IControlFactory _controlFactory;
        private readonly DMRelationship _createdRelationship;
        private readonly IPanelInfo _panelInfo;
        private readonly PanelInfo.FieldInfo _relatedClassFieldInfo;

        private readonly IPanel _createRelationshipPanel;

        public CreateRelationshipWizardStep1(DMRelationshipCreator relationshipCreator, IControlFactory controlFactory)
        {
            RelationshipCreator = relationshipCreator;
            if (relationshipCreator == null) throw new ArgumentNullException("relationshipCreator");
            if (controlFactory == null) throw new ArgumentNullException("controlFactory");
            _ownerClass = relationshipCreator.Relationship.OwnerClass;
            _controlFactory = controlFactory;
            _createdRelationship = relationshipCreator.Relationship;

            PanelBuilder panelBuilder = new PanelBuilder(controlFactory);
            IUIDef uiDef = GetUIDef();
            _panelInfo = panelBuilder.BuildPanelForForm(uiDef.UIForm);
            _panelInfo.BusinessObject = _createdRelationship;

            _createRelationshipPanel = _panelInfo.Panel;
            _relatedClassFieldInfo = _panelInfo.FieldInfos["ReverseRelationship.ClassDM"];
            RelatedClassComboBox = (IComboBox)_relatedClassFieldInfo.InputControl;
            RelatedClassComboBox.Width = 130;
            ILabel label = controlFactory.CreateLabel("");
            label.Text = "Create relationship for " +_ownerClass.ToString();
            GridLayoutManager layoutManager = new GridLayoutManager(this, controlFactory);
            layoutManager.SetGridSize(2, 1);
            layoutManager.FixAllRowsBasedOnContents();
            layoutManager.FixColumnBasedOnContents(0);
            layoutManager.AddControl(label);
            layoutManager.AddControl(_createRelationshipPanel);
            
            this.MinimumSize = _createRelationshipPanel.Size;
        }

        private static IUIDef GetUIDef()
        {
            return ClassDef.Get<DMRelationship>().UIDefCol["CreateNewStep1"];
        }

        /// <summary>
        /// initialise the wizardstep
        /// </summary>
        public override void InitialiseStep()
        {
            if (_ownerClass != null && _ownerClass.Solution != null)
            {
                RelationshipComboBoxMapper controlMapper = (RelationshipComboBoxMapper)_relatedClassFieldInfo.ControlMapper;
                BusinessObjectCollection<DMClass> allClasses = _ownerClass.Solution.AllClasses;
                if (!ReferenceEquals(controlMapper.BusinessObjectCollection, allClasses))
                {
                    controlMapper.IncludeBlankItem = true;
                    controlMapper.BusinessObjectCollection = allClasses;
                }
            }
            IsInitialised = true;
        }

        /// <summary>
        /// Can move to next wizard step
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public override bool CanMoveOn(out string message)
        {
            CheckInitialised();
            message = "";
            if (_createdRelationship.RelatedClass == null)
            {
                message = "You must select a related class";
                return false;
            }
            return true;
        }

        public override void MoveOn()
        {
            if (this.RelationshipCreator.CanFindForeignKey)
            {
                this.RelationshipCreator.SetupRelationship();
            }
            base.MoveOn();
        }

        public override void UndoMoveOn()
        {

            this.RelationshipCreator.CancelCreatedProperties();
            base.UndoMoveOn();
        }

        public override string HeaderText
        {
            get { return "Step1: Capture basic information for a new Relationship"; }
        }

        private void CheckInitialised()
        {
            if (!IsInitialised)
            {
                throw new WizardStepNotInitialised("The wizard step " + this.GetType().Name +
                                                   " is not initialised. Please ensure InitialiseStep is called prior to trying to access any methods");
            }
        }

        /// <summary>
        ///  business object that this wizard step is creating
        /// </summary>
        public DMRelationship CreatedRelationship
        {
            get
            {
//                CheckInitialised();
                return _createdRelationship;
            }
        }

        private bool IsInitialised { get; set; }

        public IComboBox RelatedClassComboBox { get; private set; }
    }
}